// 单例模式封装工具库 - 首先需要一个自调用函数
// 调用自调用函数就应该得到一个小函数 - 使用变量接收
(function(window){
    // 将类定义在这里
    class Tool{
        getRandom(a,b){
            var max = a;
            var min = b;
            if(a<b){
                max = b
                min = a
            }
            return parseInt(Math.random() * (max-min)) + min
        }
        getColor(hex=true){
            if(!hex){
                return 'rgb('+this.getRandom(256,0)+','+this.getRandom(256,0)+','+this.getRandom(256,0)+')'
            }
            var color = '#'
            for(var i=0;i<3;i++){
                var num2 = this.getRandom(256,0)
                num2 = num2.toString(16)
                if(num2.length === 1){
                    num2 = '0' + num2
                }
                color += num2
            }
            return color;
        }
        getStyle(ele,attr){
            if(window.getComputedStyle){
                return window.getComputedStyle(ele)[attr]
            }else{
                return ele.currentStyle[attr]
            }
        }
        bindEvent(ele,type,fn){
            if(ele.addEventListener){
                ele.addEventListener(type,fn)
            }else{
                ele.attachEvent('on'+type,fn)
            }
        }
        unBind(ele,type,fn){
            if(ele.removeEventListener){
                ele.removeEventListener(type,fn)
            }else{
                ele.detachEvent('on'+type,fn)
            }
        }
        setStyle(ele,styleObj){
            for(var attr in styleObj){
                ele.style[attr] = styleObj[attr]
            }
        }
        move(ele,obj,fn=function(){}){
            var k = 0
            var n = 0
            for(let attr in obj){
                k++
                let timerId = setInterval(function(){
                    var target = obj[attr]
                    var style = getStyle(ele,attr)
                    if(attr === 'opacity'){
                        style *= 100
                        target *= 100
                    }
                    style = parseInt(style)
                    var diff = target - style;
                    var speed = diff/20
                    if(speed>0){
                        speed = Math.ceil(speed)
                    }else{
                        speed = Math.floor(speed)
                    }
                    style += speed
                    if(style === target){
                        style = target
                        if(attr === 'opacity'){
                            ele.style[attr] = style/100
                        }else{
                            ele.style[attr] = style  +"px"
                        }
                        clearInterval(timerId)
                        n++
                        if(n === k){
                            fn()
                        }
                    }else{
                        if(attr === 'opacity'){
                            ele.style[attr] = style/100
                        }else{
                            ele.style[attr] = style  +"px"
                        }
                    }
                    
                },20)
            }
        }
        setCookie(key,value,seconds,path='/'){
            var date = new Date()
            date.setTime(date.getTime()-8*3600*1000+seconds*1000)
            document.cookie = `${key}=${value};expires=${date};path=${path}`
        }
        getCookie(key){
            var cookies = document.cookie;
            var arr = cookies.split('; ')
            for(var i=0;i<arr.length;i++){
                var brr = arr[i].split('=')
                if(brr[0] === key){
                    return brr[1]
                }		
            }	
        }
        removeCookie(key,path='/'){
            this.setCookie(key,null,-1,path)
        }
        sendAjax(obj){
            if(obj.url === undefined){
                throw new Error("请求地址必填")
            }
            if(Object.prototype.toString.call(obj.url) !== '[object String]'){
                throw new Error("请求地址不合法")
            }
            if(obj.method === undefined){
                obj.method = 'get'
            }
            if(obj.method !== 'get' && obj.method !== 'post'){
                throw new Error("请求方式不合法")
            }
            if(obj.async === undefined){
                obj.async = true
            }
            if(Object.prototype.toString.call(obj.async) !== '[object Boolean]'){
                throw new Error("async参数不对，必须是布尔值")
            }
            if(obj.data !== undefined){
                if(Object.prototype.toString.call(obj.data) === '[object String]'){
                    var str = obj.data
                }else if(Object.prototype.toString.call(obj.data) === '[object Object]'){
                    var str = '';
                    var f = ''
                    for(var attr in obj.data){
                        str += f + attr + '=' + obj.data[attr]
                        f = '&'
                    }
                }else{
                    throw new Error("数据必须是字符串或对象")
                }
                if(obj.method === 'get'){
                    obj.url = obj.url + '?' + str
                }
            }
            if(obj.dataType !== undefined){
                if(obj.dataType !== 'xml' && obj.dataType !== 'json'){
                    throw new Error("dataType必须是xml")
                }
            }
            if(obj.success === undefined){
                obj.success = function(){}
            }
            if(Object.prototype.toString.call(obj.success) !== '[object Function]'){
                throw new Error("success必须是函数")
            }
            if(obj.error === undefined){
                obj.error = function(){}
            }
            if(Object.prototype.toString.call(obj.error) !== '[object Function]'){
                throw new Error("error必须是函数")
            }
            var xhr = new XMLHttpRequest()
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    if(xhr.status<300 && xhr.status>=200){
                        if(obj.dataType === 'xml'){
                            var res = xhr.responseXML;
                        }else if(obj.dataType === 'json'){
                            var res = xhr.responseText;
                            res = JSON.parse(res)
                        }else{
                            var res = xhr.responseText;
                        }
                        obj.success(res)
                    }else{
                        obj.error()
                    }
                }
            }
            xhr.open(obj.method,obj.url,obj.async)
            if(obj.data && obj.method === 'post'){
                xhr.setRequestHeader("content-type",'application/x-www-form-urlencoded')
                xhr.send(str)
                return false;
            }
            xhr.send()
        }
        promiseAjax(obj){
            return new Promise(function(resolve,reject){
                if(obj.url === undefined){
                    throw new Error("请求地址必填")
                }
                if(Object.prototype.toString.call(obj.url) !== '[object String]'){
                    throw new Error("请求地址不合法")
                }
                if(obj.method === undefined){
                    obj.method = 'get'
                }
                if(obj.method !== 'get' && obj.method !== 'post'){
                    throw new Error("请求方式不合法")
                }
                if(obj.async === undefined){
                    obj.async = true
                }
                if(Object.prototype.toString.call(obj.async) !== '[object Boolean]'){
                    throw new Error("async参数不对，必须是布尔值")
                }
                if(obj.data !== undefined){
                    if(Object.prototype.toString.call(obj.data) === '[object String]'){
                        var str = obj.data
                    }else if(Object.prototype.toString.call(obj.data) === '[object Object]'){
                        var str = '';
                        var f = ''
                        for(var attr in obj.data){
                            str += f + attr + '=' + obj.data[attr]
                            f = '&'
                        }
                    }else{
                        throw new Error("数据必须是字符串或对象")
                    }
                    if(obj.method === 'get'){
                        obj.url = obj.url + '?' + str
                    }
                }
                if(obj.dataType !== undefined){
                    if(obj.dataType !== 'xml' && obj.dataType !== 'json'){
                        throw new Error("dataType必须是xml")
                    }
                }
                var xhr = new XMLHttpRequest()
                xhr.onreadystatechange = function(){
                    if(xhr.readyState === 4){
                        if(xhr.status<300 && xhr.status>=200){
                            if(obj.dataType === 'xml'){
                                var res = xhr.responseXML;
                            }else if(obj.dataType === 'json'){
                                var res = xhr.responseText;
                                res = JSON.parse(res)
                            }else{
                                var res = xhr.responseText;
                            }
                            resolve(res)
                        }else{
                            reject()
                        }
                    }
                }
                xhr.open(obj.method,obj.url,obj.async)
                if(obj.data && obj.method === 'post'){
                    xhr.setRequestHeader("content-type",'application/x-www-form-urlencoded')
                    xhr.send(str)
                    return false;
                }
                xhr.send()
            })
        }
    }
    // 定义一个对象变量
    let tool;
    // return 一个小函数
    return (function(window){
        if(!tool){
            tool = new Tool()
        }
        window.tool = window.Tool = tool;
    })(window)
})(window)